package com.hoopchina.util.search;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
//import java.net.MalformedURLException;
//import java.net.SocketTimeoutException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

import com.hoopchina.meta.NewsItem;
import com.hoopchina.util.xml.NewsItemXML;
import com.hoopchina.util.xml.XMLDataNetwork;
//import com.hoopchina.util.xml.XMLDataNetwork;

import android.content.Context;
import android.os.Handler;


/**
 * SearchHandlerThread
 * 搜索
 * 
 * @author Guo Baiyu
 * 
 */
public class SearchHandlerThread extends Thread {
    public static final String    SEARCH_ADDR             = "http://newsmobile.baidu.com/k?subpid=3";
    public static final String    TAG_SEARCH_HTTP_KEYWORD = "&word=";
    public static final String    TAG_SEARCH_HTTP_TN      = "&tn=newsXmlUTF8";
    public static final String    TAG_SEARCH_HTTP_FROM    = "&from=news&ie=gb2312";
    public static final String    TAG_SEARCH_BS           = "&bs=";
    public static final String    TAG_SEARCH_HTTP_SR      = "&sr=0";
    public static final String    TAG_SEARCH_HTTP_CL      = "&cl=";
    public static final String    TAG_SEARCH_HTTP_RN      = "&rn=";
    public static final String    TAG_SEARCH_HTTP_PN      = "&pn=";
    public static final String    TAG_SEARCH_HTTP_CT      = "&ct=0&prevct=no";
    
   // http://newsmobile.baidu.com/k?subpid=3&word=%C1%F5%B5%C2%BB%AA&tn=newsXmlUTF8&from=news&ie=gb2312&bs=%C1%F5%B5%C2%BB%AA&sr=0&cl=2&rn=20&ct=0&prevct=no
    // http://news.baidu.com/ns?word=nba&tn=newstitlexml&from=news&cl=2&rn=20&ct=1

    public static final int       MEDIA_TYPE_DEFAULT      = 0;
    public static final int       MEDIA_TYPE_FLUENTLY     = 1;
    public static final int       MEDIA_TYPE_CLEARLY      = 2;

    public static final int       H_SEARCH_RESULT_OK      = 3;
    public static final int       H_SEARCH_NOTHING        = 4;
    public static final int       H_SEARCH_NETWORK_ERROR  = 5;
    public static final int       H_SEARCH_START          = 6;
    public static final int       H_LOAD_MORE_OK	      = 7;

    public static final int       SEARCH_RETURN_NUM       = 20;

    private List<NewsItem>        mSearchResultList       = null;
    private String                mKeyWord                = null;
    private int                   mType                   = 0;
    @SuppressWarnings ( "unused" )
    private int                   mPageNo                 = 0;

    private Context               mContext                = null;
    private ISearchHandleObserver mHandleObserver         = null;

    /**
     * 
     * @param strKeyWord
     * @param type
     * @param pageNo
     */
    public SearchHandlerThread( Context context, String strKeyWord, int type, int pageNo ) {
        this.mContext = context;
        this.mKeyWord = strKeyWord;
        this.mType 	  = type;
        this.mPageNo  = pageNo;
        
        if ( this.mType == MEDIA_TYPE_DEFAULT ) {
//            mIsDefaultSearching = true;

//            ConnectivityManager connectivityManager = 
//            	( ConnectivityManager ) mContext.getSystemService( Context.CONNECTIVITY_SERVICE );

//            if ( null != connectivityManager
//                    && null != connectivityManager.getActiveNetworkInfo()
//                    && connectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI ) {
//                this.mType = MEDIA_TYPE_CLEARLY;
//            }
        }

    }
    public void setObserver(ISearchHandleObserver observer)
	{
        mHandleObserver = observer;
	}

    /**
	 * 
	 */
    public void run() {
        getSearchResultData();
    }

    /**
	 * 
	 */
    private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg)
		{
			if (null == mContext) { return; }
			switch (msg.what)
			{
			case H_SEARCH_START:
				mHandleObserver.searchStart();
				break;

			case H_SEARCH_RESULT_OK:
				mHandleObserver.searchResultShow( mSearchResultList );
				break;

			 case H_LOAD_MORE_OK:
				 mHandleObserver.searchResultRefresh( mSearchResultList );
			 break;

			case H_SEARCH_NOTHING:
				mHandleObserver.searchResultNothing();
				break;

			case H_SEARCH_NETWORK_ERROR:
				mHandleObserver.searchNetworkError();
				break;
				
			default:
                mHandleObserver.searchError();

				break;
			}
		};
	};

    /**
	 * 
	 */
    synchronized private void getSearchResultData() {
        if ( null == mContext 	
        	|| null == mKeyWord || mKeyWord.equals("")
           ) {
            return;
        }
        
        mHandler.sendEmptyMessage( H_SEARCH_START );
        
//        if ( !( DeviceInfoUtils.isWifi( mContext ) 
//                || DeviceInfoUtils.checkNet( mContext ) ) ) {
//            mHandler.sendEmptyMessage( H_SEARCH_NETWORK_ERROR );
//            return;
//        }
        
        // search api
        String utf8KeyWord = null;
        String tempWord = null; 
        URLConnection urlConnSearch = null;

        // keyword
        try {
        	
        	tempWord = mKeyWord.replaceAll( " ", "+" );
        	utf8KeyWord = URLEncoder.encode( tempWord, "GBK" );
        	
            // utf8KeyWord = URLEncoder.encode(mKeyWord, "UTF-8");
            // %C4%C7%D0%A9
            // %E9%82%A3%E4%BA%9B
        }
        catch ( UnsupportedEncodingException e1 ) {
            e1.printStackTrace();
        }
        @SuppressWarnings ( "unused" )
        String tbPara = null;
        switch ( mType ) {
            case MEDIA_TYPE_DEFAULT:
            tbPara = "";
                break;
            case MEDIA_TYPE_FLUENTLY:
            tbPara = "&tb=0";
                break;
            case MEDIA_TYPE_CLEARLY:
            tbPara = "&tb=1";
                break;
            default:
            tbPara = "";
                break;
        }
        try {
            String url = SEARCH_ADDR + TAG_SEARCH_HTTP_KEYWORD + utf8KeyWord + TAG_SEARCH_HTTP_TN
                + TAG_SEARCH_HTTP_FROM +TAG_SEARCH_BS + utf8KeyWord + TAG_SEARCH_HTTP_SR + TAG_SEARCH_HTTP_CL + 2 + TAG_SEARCH_HTTP_RN + 20 +TAG_SEARCH_HTTP_PN + mPageNo + TAG_SEARCH_HTTP_CT;

            urlConnSearch = XMLDataNetwork.getHttpConnection( url );
          //  http://newsmobile.baidu.com/k?subpid=3&word=%C1%F5%B5%C2%BB%AA&tn=newsXmlUTF8&from=news&ie=gb2312&bs=%C1%F5%B5%C2%BB%AA&sr=0&cl=2&rn=20&ct=0&prevct=no  
            // TODO:temp data<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        	//InputStream   	instreamChannelInfo = this.getClass().getClassLoader().getResourceAsStream("channellist.xml");
           
           
			//NewsItemXML searchResult = new NewsItemXML();
            mSearchResultList = NewsItemXML.getNewsList( urlConnSearch.getInputStream() );			
            // TODO:temp data<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        }
        catch ( Exception e ) {
            mHandler.sendEmptyMessage( H_SEARCH_NETWORK_ERROR );
            e.printStackTrace();
            return;
        }
//        catch ( MalformedURLException e ) {
//            e.printStackTrace();
//        }
//        catch ( IOException e ) {
//            e.printStackTrace();
//        }

        if ( null == mSearchResultList || 0 == mSearchResultList.size() ) {
            // 搜索无结果
            mHandler.sendEmptyMessage( H_SEARCH_NOTHING );
        }
        else {
            // 显示搜索结果

        	if (mType == MEDIA_TYPE_DEFAULT) {
                mHandler.sendEmptyMessage( H_SEARCH_RESULT_OK );
        	}
        	else {
                mHandler.sendEmptyMessage( H_LOAD_MORE_OK );
        	}
        } 
    }
   
}
